import type { App } from 'vue'
import * as Sentry from '@sentry/vue'

/**
 * 设置全局错误处理器
 * @param app Vue应用实例
 */
export function setupErrorHandler(app: App) {
  // Vue 错误处理器
  app.config.errorHandler = (err, instance, info) => {
    console.error('Vue Error:', err, info)
    
    // 发送到 Sentry
    Sentry.withScope((scope) => {
      scope.setTag('errorBoundary', 'vue')
      scope.setContext('errorInfo', {
        componentStack: info,
        timestamp: new Date().toISOString()
      })
      
      if (instance) {
        scope.setContext('vueComponent', {
          name: instance.$options.name || 'Unknown',
          props: instance.$props
        })
      }
      
      Sentry.captureException(err)
    })
  }

  // 全局未捕获的 Promise 错误
  window.addEventListener('unhandledrejection', (event) => {
    console.error('Unhandled Promise Rejection:', event.reason)
    
    Sentry.withScope((scope) => {
      scope.setTag('errorBoundary', 'promise')
      scope.setContext('promiseError', {
        reason: event.reason,
        timestamp: new Date().toISOString()
      })
      
      Sentry.captureException(event.reason)
    })
  })

  // 全局 JavaScript 错误
  window.addEventListener('error', (event) => {
    console.error('Global Error:', event.error)
    
    Sentry.withScope((scope) => {
      scope.setTag('errorBoundary', 'global')
      scope.setContext('globalError', {
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        timestamp: new Date().toISOString()
      })
      
      Sentry.captureException(event.error || new Error(event.message))
    })
  })

  console.log('全局错误处理器已设置')
}